package com.paxcodi.sockets.helloworld;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SimpleClient {

    /**
     * @param args host port messagestring
     */
    public static void main(String[] args) {
	if(args.length != 3){
	    System.err.println("usage:\n" + 
	    "java SimpleClient <host> <port> <msg>");
	    return;
	}
	
	String serverName = args[0];
	int serverPort = Integer.parseInt(args[1]);
	String msg = args[2];
	Socket remoteServer = null;
	
	try {
	    remoteServer = new Socket(serverName, serverPort);
	    BufferedReader in = new BufferedReader(
		    new InputStreamReader(remoteServer.getInputStream()));
	    PrintWriter out = new PrintWriter(remoteServer.getOutputStream());
	    
	    out.println(msg);
	    out.flush();
	    
	    System.out.println("Received from remote server: " + in.readLine());
	    
	} catch (UnknownHostException e) {
	    System.err.println("Cannnot find host: " + serverName + "\n" + e);
	} catch (SocketException e) {
	    System.err.println("Cannot connect to host: " + 
		    serverName + "\n" + e);
	} catch (IOException e) {
	    System.err.println(e);
	} finally {

	    try {
		if (remoteServer != null) 
		    remoteServer.close();
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}

    }
}
